import re
import time
import pymysql
#数据库地址和端口
SQL_HOST='xxx.xx.xxx.xx'
SQL_PORT=3306
#数据库用户名和密码
SQL_user='xxxx'
SQL_pass='xxxxx'
#数据库名字必须是'Hey_guys'
SQL_DBname='Hey_guys'
#控制他的qq号,主要是控制他关闭
admin_qq='123456798'
pat=re.compile(r'^\d{7}$')
def onQQMessage(bot, contact, member, content):
    if(contact.ctype!='buddy'):
        return
    time.sleep(2)
    if(contact.qq==admin_qq and content=='-stop'):
        bot.SendTo(contact, 'QQ机器人已关闭')
        bot.Stop()
        return
    print(contact.qq)
    if(pat.match(content)!=None):
        bot.SendTo(contact,'匹配成功,正在查询')
        db=pymysql.connect(host=SQL_HOST,port=SQL_PORT,user=SQL_user,password=SQL_pass,db=SQL_DBname,charset='utf8')
        cursor = db.cursor()
        try:
            sql='SELECT * FROM wait WHERE ran_code=%s'%(content)
            if(cursor.execute(sql.encode('utf8'))==0):
                bot.SendTo(contact,'没有查询到这条记录,请核对')
            else:
                result = cursor.fetchall()
                db.commit()
                if(result[0][6]!=contact.qq):
                    bot.SendTo(contact,'查询到这条记录,但是主人不是你')
                    db.close()
                    return
                for i in result:
                    sql='INSERT INTO run(ran_code,user_time,context,approach,obj_type,user_num,sub_time) VALUES(\'%d\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')'%(i[1:])
                    cursor.execute(sql.encode('utf8'))
                    db.commit()
                    sql='DELETE FROM wait WHERE id=%d'%(i[0])
                    cursor.execute(sql.encode('utf8'))
                    db.commit()
                bot.SendTo(contact,'激活成功~')
        except:
            db.rollback()
            bot.SendTo(contact,'服务器发生异常..请联系管理员')
        db.close()